export default {

  data: function () {
    return {
      ip: '',
      port: '',
      url: '',
      reconnUrl: '',
      handler: null,
      heartbeatTimeout: '',
      reconnInterval: '',
      lastInteractionTimeValue: [],
      heartbeatSendInterval: '',
      connect: null

    }
  },
  methods: {
    /**
     * @param protocol
     * @param {*} ip
     * @param {*} port
     * @param {*} handler
     * @param {*} heartbeatTimeout 心跳时间 单位：毫秒
     * @param {*} reconnInterval 重连间隔时间 单位：毫秒
     * @param {*} binaryType 'blob' or 'arraybuffer';//arraybuffer是字节
     */
    tio (protocol, ip, port, handler, heartbeatTimeout, reconnInterval, binaryType) {
      this.ip = ip
      this.port = port
      this.url = protocol + '://' + ip + ':' + port
      this.binaryType = binaryType || 'arraybuffer'
      this.reconnUrl += 'tiows_reconnect=true'

      this.handler = handler
      this.heartbeatTimeout = heartbeatTimeout
      this.reconnInterval = reconnInterval

      this.lastInteractionTime = function () {
        if (arguments.length === 1) {
          this.lastInteractionTimeValue = arguments[0]
        }
        return this.lastInteractionTimeValue
      }

      this.heartbeatSendInterval = heartbeatTimeout / 2
    },
    // 启动连接
    connect (isReconnect) {
      let _url = this.url
      if (isReconnect) {
        _url = this.reconnUrl
      }
      const ws = new WebSocket(_url)
      this.ws = ws
      const self = this

      ws.binaryType = this.binaryType // 'arraybuffer'; // 'blob' or 'arraybuffer';//arraybuffer是字节

      ws.onopen = function (event) {
        self.handler.onopen(event, ws)
        self.lastInteractionTime(new Date().getTime())

        self.pingIntervalId = setInterval(function () {
          self.ping(self)
        }, self.heartbeatSendInterval)
      }
      ws.onmessage = function (event) {
        self.handler.onmessage(event, ws)
        self.lastInteractionTime(new Date().getTime())
      }
      ws.onclose = function (event) {
        clearInterval(self.pingIntervalId) // clear send heartbeat task

        try {
          self.handler.onclose(event, ws)
        } catch (error) {
        }
        self.reconn(event)
      }
      ws.onerror = function (event) {
        self.handler.onerror(event, ws)
      }
      return ws
    },

    // 发送消息
    send (data) {
      this.ws.send(data)
    },

    reconn (event) {
      const self = this
      setTimeout(function () {
        const ws = self.connect(true)
        self.ws = ws
      }, self.reconnInterval)
    },

    ping () {
      const iv = new Date().getTime() - this.lastInteractionTime() // 已经多久没发消息了
      // 单位：秒
      if ((this.heartbeatSendInterval + iv) >= this.heartbeatTimeout) {
        this.handler.ping(this.ws)
      }
    }

  }
}
